using System.Collections;
using System.Collections.Generic;

namespace Nice157Advices.Advices
{
    /// <summary>
    /// 23、避免将List<T>作为自定义集合类的基类
    /// </summary>
    public static class _23
    {
        /*
            如果要实现一个自定义的集合类，最好不要以List<T>作为基类，而应该扩展相应的泛型接口，通常是Ienumerable<T>和ICollection<T>(或ICollection<T>的子接口，如IList<T>。
         */
        public static void Go ()
        {
            var es = new Employees ()
            {
                new Employee { Name = "capdiem" },
                new Employee { Name = "fox" },
                new Employee { Name = "lena" }
            };
            ICollection<Employee> _es = es;
            _es.Add (new Employee { Name = "tomato" });
            foreach (var item in _es)
            {
                System.Console.WriteLine (item.Name);
            }

            System.Console.WriteLine ("WRONG EMPLOYEES:");

            var wrongEs = new WrongEmployees ()
            {
                new Employee { Name = "capdiem" },
                new Employee { Name = "fox" },
                new Employee { Name = "lena" }
            };
            IList<Employee> _wrongEs = wrongEs;
            _wrongEs.Add (new Employee { Name = "banana" });
            foreach (var item in _wrongEs)
            {
                System.Console.WriteLine (item.Name);
            }
        }

        private class Employees : IEnumerable<Employee>, ICollection<Employee>
        {
            List<Employee> items = new List<Employee> ();

            public IEnumerator<Employee> GetEnumerator () => items.GetEnumerator ();

            public void Add (Employee item)
            {
                item.Name += "?";
                items.Add (item);
            }

            #region Name
            public int Count =>
            throw new System.NotImplementedException ();

            public bool IsReadOnly =>
            throw new System.NotImplementedException ();

            public void Clear ()
            {
                throw new System.NotImplementedException ();
            }

            public bool Contains (Employee item)
            {
                throw new System.NotImplementedException ();
            }

            public void CopyTo (Employee[] array, int arrayIndex)
            {
                throw new System.NotImplementedException ();
            }

            public bool Remove (Employee item)
            {
                throw new System.NotImplementedException ();
            }

            IEnumerator IEnumerable.GetEnumerator ()
            {
                throw new System.NotImplementedException ();
            }
            #endregion
        }

        private class Employee
        {
            public string Name { get; set; }
        }

        private class WrongEmployees : List<Employee>
        {
            public new void Add (Employee item)
            {
                item.Name += "?";
                base.Add (item);
            }
        }
    }
}